<?php
namespace app\common\service;

use app\common\model\BaseModel;
use app\common\model\SysSettingModel;
use Qiniu\Auth;
use think\facade\Db;

class Upload
{
//    const PREVIEW_VIEW = "http://qn.yezituina.com/";
//    const show_local_file = true;  /// true-上传本地 false-上传七牛

    const OPEN_DB_SAVE = true;

    private $user_id;
    protected $fsizeLimit=0;//文件上传大小


    protected static $use_qiniu_type = ['video'];

    private $root_path;
    public function __construct($user_id=0)
    {
        $this->user_id = $user_id;
        $this->root_path = root_path();
        $this->fsizeLimit = 1024*1024*10;
    }

    //是否使用七牛上传
    public static function getUploadQiniuState()
    {
        return SysSettingModel::getContent('qiniu','mode')=='qiniu';
    }


    private static function qiniuInfo($type):string{

        $auth = new Auth(SysSettingModel::getContent('qiniu','ak'), SysSettingModel::getContent('qiniu','sk'));
        $save_key = '/$(x:img_type)/$(year)$(mon)$(day)/$(etag)$(ext)';
        if($type=='ueditor' && !self::OPEN_DB_SAVE){
            $body = '{"state":"SUCCESS","original":$(fname),"size":$(fsize),"title":$(fname),"type":$(x:img_type),"url":"'.self::previewUrl().$save_key.'"}';
        }else{
            $is_ueditor = $type=='ueditor' ? 1 : 0;
            $body = '{"code":1,"msg":"上传成功","data":{"key":"'.self::previewUrl().$save_key.'","type":"$(x:img_type)","original":$(fname),"mime_type":"$(mimeType)","hash":"$(etag)","fsize":$(fsize),"width":"$(imageInfo.width)","height":"$(imageInfo.height)","duration":"$(avinfo.video.duration)","v_width":"$(avinfo.video.width)","v_height":"$(avinfo.video.height)","is_ueditor":"'.$is_ueditor.'"}}';
        }
        $policy = [
            'forceSaveKey'=>true,
            'saveKey' => $save_key,
            'returnBody' =>  $body,
        ];

        if(self::OPEN_DB_SAVE){ //开启回调
            $policy['callbackUrl'] =  request()->domain().'/api/upload/callback';
            $policy['callbackBody'] =  $body;
            $policy['callbackBodyType'] =  'application/json';
        }
//        dump($policy);exit;
//        dump(SysSettingModel::getContent('qiniu','bucket'));exit;
        $key=null;
        $token = $auth->uploadToken(SysSettingModel::getContent('qiniu','bucket'),$key,86400,$policy);
        return $token;
    }

    //获取上传凭证
    public static function info($type='image',array $params = [])
    {
        //是否上传本地
        $is_local = intval($params['local']??0);
        $return_json = $params['return_json']??false;
        $accept = $params['accept']??'images';
        $acceptMine = $params['acceptMine']??'images/*';
        $point_url = $params['url']??url('upload/upload',[],false,true).'?type='.$type;



        $data = [
            'accept'=>'images',
            'url' => $point_url,
            'acceptMine' => $acceptMine,
        ];
        $data['data']['token']='';
        if($is_local!=1 && self::getUploadQiniuState()){
            $data['data']['x:img_type'] = $type;
            $data['data']['token'] = self::qiniuInfo($type);
            $data['url'] = SysSettingModel::getContent('qiniu','url');
        }

        if($accept=='video'){
            $data['accept'] = 'video';
        }else{
            $data['accept'] = 'file';
        }



        return $return_json?json($data)->getContent():$data;

    }


    //上传
    public function upload($type='image',array $params = [])
    {
        //是否上传本地
        $is_local = intval($params['local']??0);

        $upload_file_key=key($_FILES);
        empty($upload_file_key) && abort(0,'请选择上传文件');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($upload_file_key);

        empty($file) && abort(0,'请选择上传文件');
        // 上传到本地服务器
        if($type=='apk'){
            $savename = \think\facade\Filesystem::putFileAs( 'android', $file,'android.apk');
        }elseif($type=='device_ad'){
            //验证文件名
            $fil_name = $file->getOriginalName();
            //文件名只能是数字跟字母+.
            if(!preg_match('/^[\w.]+$/',$fil_name)){
               abort(0,'文件名只能是字母数字或下划线');
            }
            $savename = \think\facade\Filesystem::putFileAs( 'device_ad', $file,$fil_name);
        }elseif($type=='apk_mch'){
            $savename = \think\facade\Filesystem::putFileAs( 'android', $file,'android_mch.apk');
        }elseif(stripos($type,'fixed_')!==false){
            $file_type = str_replace('fixed_',"",$type);
            $savename = \think\facade\Filesystem::putFileAs( 'fixed', $file,$file_type.'.png');
        }else{
            if(empty($file->getOriginalExtension())){
                $file_name = md5($file->getOriginalName()).'.png';
                $savename = \think\facade\Filesystem::putFileAs( $type, $file,$file_name);
            }else{
                $savename = \think\facade\Filesystem::putFile( $type, $file);
            }
        }
        $savename = str_replace('\\',"/",$savename);
        if(isset($params['abs_path'])){
            return '/uploads/'.$savename;
        }
        //上传路径
        $mime_type = $file->getOriginalMime();
        $key = self::previewUrl($is_local).'/uploads/'.$savename;
        $mime_type = stripos($mime_type,'image')!==false?'image':$mime_type;
        $data = [
            'key'=> $key,
            'mime_type' => $mime_type,
            'fsize' => $file->getSize(),
        ];

        //保存上传图片
        self::saveImage([
            'type' => $type,
            'key' => $key,
            'hash' => $file->hash(),
            'mime_type' => $mime_type,
            'fsize' => $file->getSize(),
        ]);

        return $data;
    }

    //保存图片
    public static function saveImage(array $input_data = [])
    {
        Db::table('sys_file_manager')->save([
            'type' => $input_data['type']??null,
            'mime_type' => $input_data['mime_type']??null,
            'key' => $input_data['key']??'',
            'hash' => $input_data['hash']??null,
            'fsize' => $input_data['fsize']??null,
            'width' => $input_data['width']??null,
            'height' => $input_data['height']??null,
            'duration' => $input_data['duration']??null,
            'v_width' => $input_data['v_width']??null,
            'v_height' => $input_data['v_height']??null,
            'status' => 0,
        ]);
    }


    public static function previewUrl($is_local=null)
    {
        $url = request()->domain();
        if($is_local!=1 && self::getUploadQiniuState()){
            $url = SysSettingModel::getContent('qiniu','preview_url');
        }
        return $url;
    }
}